package com.zhang.user.thrift;


import com.zhang.thrift.user.UserService;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

/**
 * Created by Michael on 2017/10/28.
 * 还要启动thriftServer服务类，启动暴露thrift服务
 */
@Configuration
@Slf4j
public class ThriftServer {

    //注入配置文件application里面的值  和原版改了
    @Value("${server.port}")
    private int servicePort;

    @Autowired
    private UserService.Iface userService;  //无法加注解会误报

    @PostConstruct   //spring启动时就就启动thrift服务
    public void startThriftServer() {

        TProcessor processor = new UserService.Processor<>(userService);  // 将我们的service注册到thrift的执行器
        //网络
        TNonblockingServerSocket socket = null;
        try {
            socket = new TNonblockingServerSocket(servicePort);
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        //构建server启动的参数
        TNonblockingServer.Args args = new TNonblockingServer.Args(socket);
        args.processor(processor);  //执行器
        args.transportFactory(new TFramedTransport.Factory()); //传输方式
        args.protocolFactory(new TBinaryProtocol.Factory());  //传输协议

        TServer server = new TNonblockingServer(args); //构建server
        log.info("user-thrift-server:ThriftServer start begin on 8011");
        server.serve();  //启动server
        log.info("user-thrift-server:ThriftServer start on 8011");
    }
}
